;
(function (win, doc) {
    var oImgList = doc.getElementsByClassName('J_imgList')[0],
        data = JSON.parse(doc.getElementById('J_data').innerHTML),
        imgTpl = doc.getElementById('J_imgTpl').innerHTML,
        oImgs = doc.getElementsByClassName('list-img')

    var init = function () {
        oImgList.innerHTML = renderList(data)
        bindEvent()
        setTimeout(function () {
            win.scrollTo(0, 0)
        }, 150)
    }

    init()

    function bindEvent() {
        win.onload = win.onscroll = throttle(imgLazyLoad(oImgs), 1000)
    }

    function renderList(data) {
        var list = ''
        data.forEach(function (ele) {
            list += imgTpl.replace(/{{(.*?)}}/g, function (node, key) {
                return {
                    img: ele.img,
                    name: ele.name,
                } [key]
            })
        });
        return list
    }

})(window, document)

function imgLazyLoad(images) {
    var imgLen = images.length,
        n = 0
    return function () {
        var cHight = document.documentElement.clientHeight,
            sTop = document.documentElement.scrollTop || document.body.scrollTop,
            imgItem
        for (var i = n; i < imgLen; i++) {
            imgItem = images[i]
            if (imgItem.offsetTop < cHight + sTop) {
                imgItem.src = imgItem.getAttribute('data-src')
                imgItem.removeAttribute('data-src')
                n++
            }
        }
    }
}

function throttle(func, wait, options) {
    var timeout, context, args, result;
    var previous = 0;
    if (!options) options = {};

    var later = function () {
        previous = options.leading === false ? 0 : new Date().getTime();
        timeout = null;
        func.apply(context, args);
        if (!timeout) context = args = null;
    };

    var throttled = function () {
        var now = new Date().getTime();
        if (!previous && options.leading === false) previous = now;
        var remaining = wait - (now - previous);
        context = this;
        args = arguments;
        if (remaining <= 0 || remaining > wait) {
            if (timeout) {
                clearTimeout(timeout);
                timeout = null;
            }
            previous = now;
            func.apply(context, args);
            if (!timeout) context = args = null;
        } else if (!timeout && options.trailing !== false) {
            timeout = setTimeout(later, remaining);
        }
    };

    throttled.cancel = function () {
        clearTimeout(timeout);
        previous = 0;
        timeout = null;
    };

    return throttled;
}